from io import BytesIO

import pydicom
import requests
from requests.auth import HTTPBasicAuth
from concurrent.futures import ThreadPoolExecutor


class PacsLoader():
    def __init__(self):
        host = '106.14.28.252'
        port = 8042
        username = 'admin'
        password = '123456'
        self.base_url = f"http://{host}:{port}"
        self.auth = HTTPBasicAuth(username, password) if username and password else None

    def get_all_patients(self):
        """获取所有患者"""
        response = requests.get(f"{self.base_url}/patients", auth=self.auth)
        return response.json()

    def get_patient_studies(self, patient_id):
        """获取患者的所有检查"""
        response = requests.get(f"{self.base_url}/patients/{patient_id}/studies", auth=self.auth)
        return response.json()

    def get_study_series(self, study_id):
        """获取检查的所有序列"""
        response = requests.get(f"{self.base_url}/studies/{study_id}/series", auth=self.auth)
        return response.json()

    def get_series_instances(self, series_id):
        """获取序列的所有实例"""
        response = requests.get(f"{self.base_url}/series/{series_id}/instances", auth=self.auth)
        return response.json()

    def get_instance_dicom(self, instance_id):
        """获取实例的DICOM数据"""
        response = requests.get(
            f"{self.base_url}/instances/{instance_id}/file",
            auth=self.auth,
            stream=True
        )
        return pydicom.dcmread(BytesIO(response.content))


if __name__ == '__main__':
    loader = PacsLoader()
    patients = loader.get_all_patients()
    studies = loader.get_patient_studies(patients[0])
    for study in studies:
        series_list = loader.get_study_series(study.get('ID'))
        for series in series_list:
            print(series.get('ID'))
            # instances = loader.get_series_instances()


def load_from_pacs():
    series_id = "bc1d9fa7-0ebd9e18-30f4621a-2698b4d3-da81681a"
    loader = PacsLoader()
    instances = loader.get_series_instances(series_id)
    slices = []
    for instance in instances:
        instance_id = instance.get('ID')
        dicom_data = loader.get_instance_dicom(instance_id)
        slices.append(dicom_data)
    return slices
